<?php if( ! defined('BASEPATH')) exit('No direct script access allowed');
/* ************************************************** *\
 * @company		: NovaITech							  *	
 * @author		: van.vo@novaitech.com				  * 
 * @copyright	: 2012								  * 
 * ================================================== *
 * @date		: 2/25/2012
 * @project		: CodeGenerater
 * @description	:
 *		- 
 *
\* ************************************************** */

class MY_Controller extends CI_Controller
{
    /* ------------------------------------------------------------ *\
     | - FUNC Purpose	: Initialize libraries.
     | - Parameters		: 
     |		Name			Type		Description
     |		---------------------------------------------------
     |		N/A
     |								
     | - Return			: 
     |			- N/A 
    \* ------------------------------------------------------------ */
	function __construct()
	{
		parent::__construct();
        $this->load->database();
		$this->load->model( 'CodeGenerator_model', '', TRUE );
        $this->load->library(array('form_validation', 'table', 'session', 'pagination'));
        $this->load->helper(array('form', 'file', 'url', 'html', 'forms_helper', 'files_helper', 'array_helper','functions'));
        date_default_timezone_set('Asia/Bangkok');		
	}
	
	function autoThemPhatSinh(){
		$time = date("m/Y",time());
		$this->data['time'] = $time;	
		$limit = $this->getLimit("M","06/".$time);
		$sql = "select PS_ID from phatsinh where Create_dt >= ".$limit['datemin']." and Create_dt <= ".$limit['datemax'];
		$results = $this->CodeGenerator_model->custom_query($sql,"array");
		if(empty($results)){
			$sql = "select PS_ID,Content,Price from phatsinh where auto = 1 ";
			$results= $this->CodeGenerator_model->custom_query($sql,"array");
			$create_dt = time();
			foreach($results as $item){
				//them phat sinh
				$data = array(
                    'Content' => $item['Content'],
					'Price' => $item['Price'],
					'Create_Dt' => $create_dt
				);
				$this->CodeGenerator_model->add( 'phatsinh', $data, 'PS_ID' );
			}
		}
	}
	
	function load_template(){
		$this->load->library( 'template' );
        $this->template->set_template( 'default' );     
		$txtSearch = $this->input->post('txtSearch');
		$this->data['txtSearch']=$txtSearch;
		$this->data['username']=$this->session->userdata('username');
		$this->data['controller']=$this->uri->segment( 1 );
		$this->data['function']=$this->uri->segment( 2 );
		if(!$this->checkpermission() && !$this->data['username']) show_404();
		$this->template->add_js( 'JS/jquery-1.7.1.js' );
        $this->template->add_js( 'JS/jquery-ui-1.8.18.custom.min.js' );			
        $this->template->add_js( 'JS/styletable.js' );			
        $this->template->add_js( 'JS/js.js' );			
        $this->template->add_js( 'JS/jquery.ba-hashchange.min.js' );			
        $this->template->add_js( 'resources/menu/jquery/jMenu.jquery.js' );			
        $this->template->add_js( 'JS/jquery.bpopup.min.js' );			
        $this->template->add_js( 'resources/custom-scrollbar-plugin/jquery.mCustomScrollbar.concat.min.js' );			
		$this->template->add_css( 'CSS/style.css' );
		$this->template->add_css( 'CSS/themes/eggplant/jquery-ui.css' );
		$this->template->add_css( 'resources/menu/jquery/jMenu.jquery.css' );
		$this->template->add_css( 'CSS/autocomplete.css' );
		$this->template->add_css( 'resources/custom-scrollbar-plugin/jquery.mCustomScrollbar.css' );
		$role = $this->session->userdata('role');
		if(empty($role)) $role = 1;
		$sql = "select * from menu where sub = 0";
		$menu_array = $this->CodeGenerator_model->custom_query($sql,"array");
		$menu_new = array();
		for($i=0;$i<count($menu_array);$i++){
			$menu_array[$i]['active'] ="";
			$sub = $menu_array[$i]['id'];
			$sql = "select * from menu where sub = $sub order by name";
			
			$sub_menu = $this->CodeGenerator_model->custom_query($sql,"array");
			foreach($sub_menu as $k=>$item){
				if(!($item['permit']&$role)) unset($sub_menu[$k]);
			}
			$menu_array[$i]['child'] = $sub_menu;
			if($menu_array[$i]['permit']&$role) {
				$menu_new[] = $menu_array[$i];
			}
		}
		
		$menu_array = $menu_new;
		

		/*
		$menu_array=array(
			array("name"=>"Trang chủ","permit"=>1,'url'=>''),
			array("name"=>"Quản lý","permit"=>1,'child'=>array(
					array("name"=>"Danh mục","permit"=>1,'url'=>'categories'),
					array("name"=>"Dịch vụ","permit"=>1,'url'=>'services'),
					array("name"=>"Khách hàng","permit"=>1,'url'=>'customer'),
					array("name"=>"Khuyến mãi","permit"=>1,'url'=>'promotion'),
					array("name"=>"Nhân viên","permit"=>2,'url'=>'employee')
				)),
			array("name"=>"Tài khoản","permit"=>1,'child'=>array(
					array("name"=>"Tài khoản của tôi","permit"=>1,'url'=>'employee/myprofile')
				)),
			array("name"=>"Cài đặt","permit"=>1,'child'=>array(
					array("name"=>"Báo cáo","permit"=>1,'url'=>'report'),
					array("name"=>"Phân quyền","permit"=>2,'url'=>'permission'),
					array("name"=>"Thống kê","permit"=>2,'url'=>'statistic')
				)),
			array("name"=>"Giao dịch","permit"=>1,'url'=>'transaction'),
		);
		*/
		$controler = $this->uri->segment( 1 );
		$function = $this->uri->segment( 2 );

		
		
		if(!$controler) $menu_array[0]['active'] ="active";
		else{
			if($function == "myprofile" && $controler =='employee') $menu_array[2]['active'] ="active";
			if($function != "myprofile" && $controler =='employee') $menu_array[1]['active'] ="active";
			if($controler =="categories" || $controler =="services" || $controler =="customer" || $controler =="promotion"|| $controler =="phatsinh"|| $controler =="thuchi") $menu_array[1]['active'] ="active";
			if($controler =="report") $menu_array[3]['active'] ="active";
			if($controler =='transaction') $menu_array[4]['active'] ="active";
		}
		$this->data['menu'] = $menu_array;
		
		$this->template->write_view( 'header', "template/header.php",$this->data);
		$this->template->write_view( 'footer', "template/footer.php");
	}
	 
	
	function checkpermission(){
		$controler = $this->uri->segment( 1 );
		$function = $this->uri->segment( 2 );
		$role = $this->session->userdata('role');
		$username=$this->session->userdata('username');
		if(empty($username)) return true;
		if(empty($role)) $role = 0;
		if($function == "myprofile" && $controler =='employee') $where ="employee/myprofile";
		else $where = $controler;
		if(empty($where)) return true;
		$sql = "select * from menu where url = '$where'";
		$menu = $this->CodeGenerator_model->custom_query($sql,"array");
		if(!empty($menu)) return $role & $menu[0]['permit'];
		return 0;
	}
	
	function xl_str_duplacate($str,$param){
		$arr = explode($param,$str);
		$arr_ =array();
		foreach($arr as $item){
			if(!in_array($item, $arr_) && !empty($item)){
				$arr_[]=$item;
			}
		}
		return implode($param,$arr_);
	}
	
	
	
	function getTienTip($datemin='',$datemax=''){
		$tientip= 0;
		$arr_in = $this->getTranNotCompleted();
		if(empty($datemin) || empty($datemax)) return $tientip;
		$sql = "select sum(Price) as total from tientip where Tran_ID not in $arr_in and Create_Dt >= ".$datemin." AND Create_Dt <= ".$datemax;
		$result = $this->CodeGenerator_model->custom_query($sql,"array");
		if(!empty($result)) $tientip+= $result[0]['total'];
		
		$sql = "select sum(TienTip) as total from phieukh where Tran_ID not in $arr_in and Active = 1 and Saved=1 and Create_Dt >= ".$datemin." AND Create_Dt <= ".$datemax;
		$result = $this->CodeGenerator_model->custom_query($sql,"array");
		if(!empty($result)) $tientip+= $result[0]['total'];
		
		return $tientip;
	}
	//return string (..,..,..)
	function getTranNotCompleted(){
		$str_in = "(";
		$sql = "select Tran_ID from transaction where Completed != 2";
		$results = $this->CodeGenerator_model->custom_query($sql,"array");
		foreach($results as $itm){
			$str_in .="'".$itm['Tran_ID']."',";
		}
		if(!empty($results))
			$str_in = substr($str_in,0,-1).")";
		else $str_in = "('')";
		return $str_in;
	}
	
	function getPercentService($datemin='',$datemax=''){
		$percent_service= 0;
		$arr_in = $this->getTranNotCompleted();
		if(empty($datemin) || empty($datemax)) return $percent_service;
		$sql = "select sum(Price_Serv) as total from tientip where Tran_ID not in $arr_in and Create_Dt >= ".$datemin." AND Create_Dt <= ".$datemax;
		$result = $this->CodeGenerator_model->custom_query($sql,"array");
		if(!empty($result)) $percent_service+= $result[0]['total'];
		
		$sql = "select sum(Price_Serv) as total from phieukh where Tran_ID not in $arr_in and Active = 1 and Saved  =1 and Create_Dt >= ".$datemin." AND Create_Dt <= ".$datemax;
		$result = $this->CodeGenerator_model->custom_query($sql,"array");
		if(!empty($result)) $percent_service+= $result[0]['total'];
		
		return $percent_service;
	}
	
	function getKHCu($datemin='',$datemax=''){
		$rs= 0;
		if(empty($datemin) || empty($datemax)) return $rs;
		$sql = "select t.Cust_ID from transaction as t,customer as c where t.Completed = 2 and t.Cust_ID=c.Cust_ID and t.Create_Dt >= ".$datemin." AND t.Create_Dt <= ".$datemax." and c.Create_Dt < ".$datemin." Group by t.Cust_ID";
		$result = $this->CodeGenerator_model->custom_query($sql,"array");
		
		$rs= count($result);
		return $rs;
		
	}
	
	function getKH($datemin='',$datemax=''){
		$rs= 0;
		if(empty($datemin) || empty($datemax)) return $rs;
		$sql = "select t.Cust_ID from transaction as t where t.Completed = 2 and t.Create_Dt >= ".$datemin." AND t.Create_Dt <= ".$datemax." Group by t.Cust_ID";
		$result = $this->CodeGenerator_model->custom_query($sql,"array");
		$rs= count($result);
		return $rs;
		
	}
	
	function PercentService($EE_ID=''){
		$is = 0;
		if(empty($EE_ID)) return $is;
		$sql="select EE_ID from employee where EE_ID='$EE_ID' and Dichvu=1";
		$result = $this->CodeGenerator_model->custom_query($sql,"array");
		if(!empty($result)) $is=1;
		return $is;
	}
	
	function getResultsDichVu($datemin,$datemax){
		$sql = "select e.Personal_ID,e.Salary,e.EE_ID from employee as e where e.role=".EMPLOYER." AND e.Personal_ID != 'test' GROUP BY e.Personal_ID";
		// die($sql);
		$sum_dv = 0;
		$results = $this->CodeGenerator_model->custom_query($sql,"array");
		$arr_in = $this->getTranNotCompleted();
		foreach($results as $k =>$item){
			$ee_id = $item['EE_ID'];
			$results[$k]['Price_Serv'] = 0;
			$dv = 0;
			$sql = "select sum(Price_Serv) as total from tientip where Tran_ID not in $arr_in and EE_ID='$ee_id' and Create_Dt >= $datemin and Create_Dt <= $datemax and Vip=0";
			$total = $this->CodeGenerator_model->custom_query($sql,"array");
			if(!empty($total)) $dv += $total[0]['total'];
			
			$sql = "select sum(Price_Serv) as total from phieukh where EE_ID='$ee_id' and Tran_ID not in $arr_in and Create_Dt >= $datemin and Create_Dt <= $datemax and Active=1";
			$total = $this->CodeGenerator_model->custom_query($sql,"array");
			if(!empty($total)) $dv += $total[0]['total'];
			
			$sql = "select sum(tv.Price_Serv) as total from transaction_vip as tv, tientip as tt where tt.Tran_ID not in $arr_in and tt.ID = tv.TienTip_ID and tv.EE_ID='$ee_id' and tv.Create_Dt >= $datemin AND tv.Create_Dt <= $datemax";
			$total = $this->CodeGenerator_model->custom_query($sql,"array");
			if(!empty($total)) $dv += $total[0]['total'];
			$results[$k]['Price_Serv'] = $dv;
			$sum_dv +=$dv;
			$results[$k]['thanhtien'] = $item["Salary"]+$results[$k]['Price_Serv'];
		}
		
		$data['rows'] = $results;
		$data['sum_dv'] = $sum_dv;
		return $data;
	}
	
	function getResultsTienTip($datemin,$datemax){
		$sql = "select EE_ID, Personal_ID,Name,Salary from employee where role = 1 and active = 1 and Personal_ID!='test' and Name!='test'";
		$results = $this->CodeGenerator_model->custom_query($sql,"array");
		$sum_tt = 0;
		$arr_in = $this->getTranNotCompleted();
		foreach($results as $k=> $item){
			$ee_id = $item['EE_ID'];	
			$price_serv = 0 ;
			$sql = "select sum(tt.Price) as total from tientip as tt where tt.Tran_ID not in $arr_in and tt.EE_ID='$ee_id' and tt.Create_Dt >= $datemin AND tt.Create_Dt <= $datemax";
			$result = $this->CodeGenerator_model->custom_query($sql,"array");
			if(!empty($result)) $price_serv +=$result[0]['total'];
			$sql = "select sum(p.TienTip) as total from phieukh as p where p.Tran_ID not in $arr_in and p.Active = 1 and p.EE_ID='$ee_id' and p.Create_Dt >= $datemin AND p.Create_Dt <= $datemax";
			$result = $this->CodeGenerator_model->custom_query($sql,"array");
			if(!empty($result)) $price_serv +=$result[0]['total'];
			$sql = "select sum(tv.Price) as total from transaction_vip as tv, tientip as tt where tt.Tran_ID not in $arr_in and tt.ID = tv.TienTip_ID and tv.EE_ID='$ee_id' and tv.Create_Dt >= $datemin AND tv.Create_Dt <= $datemax";
			$result = $this->CodeGenerator_model->custom_query($sql,"array");
			if(!empty($result)) $price_serv +=$result[0]['total'];
			$sum_tt +=$price_serv;
			$results[$k]['Price'] = $price_serv;
		}
		
		$data['results'] = $results;
		$data['sum_tt'] = $sum_tt;
		return $data;
	}
	
	function setSession($result){
		if(!empty($result)){
			$this->session->set_userdata('username',$result->Personal_ID);					
			$this->session->set_userdata('role',$result->role);					
		}
	}
	
	public function Phone_Number_check($str)
	{
		if(empty($str)) return true;
		//$str = implode("",file("http://www.google.com/intl/en/contact/index.html"));
		if(strlen($str)==10){
			return preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "$1-$2-$3", $str);
		}
		$Phone_Pattern ="/(\d)?(\s|-)?(\()?(\d){3}(\))?(\s|-){1}(\d){3}(\s|-){1}(\d){4}/";
		preg_match_all($Phone_Pattern,$str,$phone);
		$result=false;
		for($i=0;$i<count($phone[0]);$i++)
		{
			$result=true;
		}
		
		if($result==false){			
			$this->form_validation->set_message('Phone_Number_check', 'Phone number is format xxx-xxx-xxxx.');
			//return preg_replace("/([0-9]{3})([0-9]{3})([0-9]{4})/", "$1-$2-$3", $str);
		}
		return $result;
	}
	
	
	/**
	* @date: timetime
	*/
	function getLimit($imgFlag='D', $date){
	// function getLimit(){
		// print_r($date);
		$data=array('datemin'=>'','datemax'=>'');
		/* test * /
		$imgFlag="Y";
		$date = date("Y-m-d H:i:s");   
		/* end test */
		//$timestamp = strtotime($date);
		$date =  strtotime(str_replace(array("/"),array("."),$date));
		// print_r($date);
		// die();
		$timestamp = $date;
		
		$date = date("Y-m-d H:i:s",$timestamp);  
		$y = date('Y', $timestamp); 
		$m = date('m', $timestamp); 
		$d = date('d', $timestamp);
		switch($imgFlag){
			case 'D':
			case 'd':
				$data['datemin']="$y-$m-$d 00:00:00";
				$data['datemax']="$y-$m-$d 23:59:59";
			break;
			case 'W':
			case 'w':
				$start_date="";
				$end_date="";
				$this->_x_week_range($start_date,$end_date,$date);			
				$data['datemin']="$start_date 00:00:00";
				$data['datemax']="$end_date 23:59:59";
			break;
			case 'M':
			case 'm':
				$d_end=cal_days_in_month(CAL_GREGORIAN, $m, $y);
				$data['datemin']="$y-$m-01 00:00:00";
				$data['datemax']="$y-$m-$d_end 23:59:59";
				break;
			case 'Y':
			case 'y':
				$data['datemin']="$y-01-01 00:00:00";
				$data['datemax']="$y-12-31 23:59:59";
			break;
		}
		$data['datemin']=strtotime($data['datemin']);
		$data['datemax']=strtotime($data['datemax']);
		return $data;
	}
	function _x_week_range(&$start_date, &$end_date, $date)
	{
		$start_date = '';
		$end_date = '';
		$week = date('W', strtotime($date));
		$week = $week;

		$start_date = $date;

		$i = 0;
		while(date('W', strtotime("-$i days")) >= $week) {
			$start_date = date('Y-m-d', strtotime("-$i day"));
			$i++;
		}
		 // $arr=explode('-', $start_date);
		 // if(count($arr)==3)
			// list($yr, $mo, $da) = explode('-', $start_date);
		// else
			// list($yr, $mo, $da) = explode('/', $start_date);
		
		$end_date = date('Y-m-d', strtotime("$start_date +6 days"));
		//chinh date mm/dd/yy --> yy-mm-dd
		$arr=explode('/', $start_date);		
		if(count($arr)==3) $start_date=$arr[2]."-".$arr[0]."-".$arr[1];
	}
	
	//27/05/2013 --> Y-m-d --> time stamp
	//start =0 : date '00:00:0' ; =1: 23:59:59
	function convertDatetoTimeStamp($date,$start){
		// $date = '27/05/2013';
		if($start) $s_h= '00:00:00';
		else $s_h='23:59:59';
		$arr = explode('/',$date);
		$timestamp = strtotime($arr[2]."-".$arr[1]."-".$arr[0]." $s_h");
		return $timestamp;
	}
	
}